package ldh.im.fxbase.dao;

import ldh.im.fxbase.data.dto.SearchResult;
import ldh.im.fxbase.data.pojo.ImSession;
import ldh.im.fxbase.util.BeanFactory;
import ldh.im.fxbase.util.DbUtil;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ImContentSearchDao {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImContentSearchDao.class);

    public List<SearchResult> searchUsers(String content) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select u.userId, u.userName from im_user u where u.userName like ?");
            List<SearchResult> searchResults = queryRunner.query(connection, sql, new BeanListHandler<SearchResult>(SearchResult.class), "%" + content + "%");
            return searchResults;
        });
    }

    public long searchUserTotal(String content) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select count(*) from im_user u where u.userName like ?");
            long total = queryRunner.query(connection, sql, new ScalarHandler<Long>(), "%" + content + "%");
            return total;
        });
    }

    public List<SearchResult> searchGroups(String userId, String search) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String searchParam = "%" + search + "%";
            String sql1 = String.format("select code groupCode, name groupName, null userId, null userName from im_group where currentUserId = ? and name like ?");
            String sql2 = String.format("select g.code groupCode, g.name groupName, u.userId userId, u.userName userName from im_group g, im_group_user gu, im_user u where g.id = gu.groupId " +
                    "and gu.userId = u.userId and g.currentUserId = ? and u.userName like ?");

            String sql = String.format("(%s) union (%s)", sql1, sql2);
            LOGGER.info("searchGroups sql: {}", sql);
            List<SearchResult> searchResults =  queryRunner.query(connection, sql, new BeanListHandler<>(SearchResult.class), userId, searchParam, userId, searchParam);
            return searchResults;
        });
    }

    public List<SearchResult> searchMessages(String userId, String content) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select m.sessionId sessionId, count(*) messageTotal from im_message m where m.currentUserId = ? and m.content like ? group by m.sessionId");
            List<SearchResult> searchResults = queryRunner.query(connection, sql, new BeanListHandler<SearchResult>(SearchResult.class), userId, "%" + content + "%");

            List<Long> sessionIds = searchResults.stream().map(s->s.getSessionId()).collect(Collectors.toList());
            ImSessionDao sessionDao = BeanFactory.getInstance().getBean(ImSessionDao.class);

            List<ImSession> sessions = sessionDao.getSessionByIds(sessionIds);
            Map<Long, ImSession> sessionIdMap = sessions.stream().collect(Collectors.toMap(ImSession::getId, Function.identity()));
            searchResults.forEach(s->s.setImSession(sessionIdMap.get(s.getSessionId())));
            return searchResults;
        });
    }

    public long searchMessageTotal(String userId, String content) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select count(*) from im_message m where u.currentUserId = ? and u.content like ?");
            long total = queryRunner.query(connection, sql, new ScalarHandler<Long>(), userId, "%" + content + "%");
            return total;
        });
    }
}
